<template>
    <yh-dialog
        :visible.sync="visibleTemp"
        v-bind="$attrs"
        :title="dialogTitle"
        :modal="false"
        :close-on-click-modal="false"
        drag
        zoomable
        width="950px"
        @close="handleCloseDialog"
    >
        <div class="dialog-main">
            <el-form label-width="120px">
                <div>
                    <el-form-item label="报警规则名称:" required>
                        <el-input v-model="submitForm.alertrtName" :disabled="isLook" clearable size="mini"></el-input>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="告警渠道:" required>
                        <el-select v-model="submitForm.alerterType" :disabled="isLook" size="mini">
                            <el-option value="email" label="邮件"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
                <!-- 邮件告警 -->
                <div class="title-with-box">
                    <el-divider content-position="left">邮件告警</el-divider>
                    <el-form label-width="120px">
                        <el-row>
                            <el-form-item label="接收人:" required>
                                <el-select
                                    placeholder="请选择或输入邮箱"
                                    multiple
                                    filterable
                                    allow-create
                                    default-first-option
                                    v-model="submitForm.receiveUserList"
                                    @change="$forceUpdate()"
                                    :disabled="isLook"
                                    size="mini"
                                    style="width: 100%"
                                >
                                    <el-option v-for="item in userStorage" :key="item.userCode" :label="item.userNickName" :value="item.userCode">
                                        <!-- <span style="float: left">{{ item.userName + ' ' + item.userNickName }}</span>
                                        <el-tooltip placement="left">
                                            <div slot="content">{{ item.roleName.join(',') }}</div>
                                            <span class="select-text"> {{ item.roleName.join(',') }} </span>
                                        </el-tooltip> -->
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="抄送人:">
                                <el-select
                                    placeholder="请选择或输入邮箱"
                                    multiple
                                    filterable
                                    allow-create
                                    default-first-option
                                    v-model="submitForm.copyUserList"
                                    @change="$forceUpdate()"
                                    :disabled="isLook"
                                    size="mini"
                                    style="width: 100%"
                                >
                                    <el-option v-for="item in userStorage" :key="item.userCode" :label="item.userNickName" :value="item.userCode">
                                        <!-- <span style="float: left">{{ item.userName + ' ' + item.userNickName }}</span>
                                        <el-tooltip placement="left">
                                            <div slot="content">{{ item.roleName.join(',') }}</div>
                                            <span class="select-text"> {{ item.roleName.join(',') }} </span>
                                        </el-tooltip> -->
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="邮件主题:" required>
                                <el-input v-model="submitForm.title" :disabled="isLook" size="mini"></el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="邮件正文:" required>
                                <el-input v-model="submitForm.context" :disabled="isLook" type="textarea" size="mini"></el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="发送规则:" required>
                                <template slot="label">
                                    <span>
                                        <el-tooltip>
                                            <div slot="content" style="white-space: pre">{{ questionTip1 }}</div>
                                            <i class="el-icon-question"></i>
                                        </el-tooltip>
                                        发送规则:
                                    </span>
                                </template>
                                <el-input
                                    v-model="submitForm.sendRule"
                                    :disabled="isLook"
                                    id="put"
                                    :autosize="{ minRows: 8 }"
                                    type="textarea"
                                    size="mini"
                                    style="width: calc(100% - 95px)"
                                ></el-input>
                                <el-button
                                    size="mini"
                                    icon="el-icon-copy-document"
                                    style="padding: 69px 15px; margin-left: 4px; vertical-align: top"
                                    @click="copyText"
                                >
                                    复制
                                </el-button>
                            </el-form-item>
                        </el-row>
                        <!-- <el-row>
                            <el-form-item label="容忍时间:" required>
                                <el-input v-model="submitForm.time" type="number" :disabled="isLook" size="mini"></el-input>
                            </el-form-item>
                        </el-row> -->
                        <el-row>
                            <el-form-item label="告警时段:">
                                <el-time-picker
                                    is-range
                                    v-model="times"
                                    :disabled="isLook"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    placeholder="选择时间范围"
                                    value-format="HHmmss"
                                    format="HH:mm:ss"
                                    size="mini"
                                >
                                </el-time-picker>
                            </el-form-item>
                        </el-row>
                    </el-form>
                </div>
            </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" v-show="type !== 'look'" @click="handleReset"> 重 置 </el-button>
            <el-button size="mini" @click="handleCloseDialog"> 取 消 </el-button>
            <el-button size="mini" v-show="type !== 'look'" :loading="loading" type="primary" @click="handleSave"> 确 认 </el-button>
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import { AlerterVO } from '../vo/monitor-rule-setting';

@Component({ name: 'AlerterDialog', components: {} })
export default class AlerterDialog extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop() detail: any;
    @Prop() type: string; // add | look
    @Prop() totalData: any; // 总数据
    @Prop() dataComparatorList: any; // 比较器数据
    @Prop() OreceiveUser: any[];
    @Prop() OcopyUser: any[];

    public visibleTemp: boolean = false;

    submitForm: AlerterVO = {
        alertrtName: '',
        alerterType: 'email', // 告警渠道
        receiveUserList: [], // 接收人
        receiveUser: '',
        copyUserList: [], // 抄送人
        copyUser: '',
        title: '', // 标题
        context: '', // 邮件正文
        sendRule: '', // 发送规则
        beginTime: null, // 告警时段-开始时间
        endTime: null, // 告警时段-结束时间
    };
    times = null;

    loading: boolean = false;

    indexArr: any[] = [{ dictKey: '', dictKeyName: '' }]; // 列选择

    userStorage: any[] = [];

    questionTip1: string =
        '通过数据汇总结果，进行数据列与列之间的数据比较，通过表达式配置，表达式成立的数据行则发送邮件通知，否则不发送\n例子：RISK_C_STOCK_CODE=HS_C_STOCK_CODE && RISK_C_STOCK_TYPE=HS_C_STOCK_TYPE\n运算符：并且：&&、或者：||、大于：>、小于：<、不等于：!=、等于：=';

    created() {}

    async mounted() {
        if (['look', 'edit'].includes(this.type)) {
            this.submitForm = JSON.parse(JSON.stringify(this.detail));
            if (this.submitForm.beginTime) {
                this.times = [this.submitForm.beginTime.toString(), this.submitForm.endTime.toString()];
            }
            if (this.submitForm.copyUser) {
                this.submitForm.copyUserList = JSON.parse(this.submitForm.copyUser);
            }
            if (this.submitForm.receiveUser) {
                this.submitForm.receiveUserList = JSON.parse(this.submitForm.receiveUser);
                console.log(this.submitForm.receiveUserList, 'this.submitForm.receiveUserList');
            }

            console.log(this.submitForm, 'this.submitForm');
        }

        // 自动生成邮件配置
        if (this.type === 'auto') {
            this.submitForm.alertrtName = this.totalData.ruleName;
            this.submitForm.title = this.totalData.ruleName;
            this.submitForm.context = this.totalData.ruleName;
            if (this.dataComparatorList && this.dataComparatorList.length) {
                this.submitForm.sendRule = '!(' + this.dataComparatorList[0].checkRuleContext + ')';
            }
            this.times = ['080000', '180000'];

            this.submitForm.copyUserList = ['test@yhfin.com'];
            this.submitForm.receiveUserList = ['test@yhfin.com'];
        }

        await this.getUserList();
    }

    @Watch('visible', { immediate: true, deep: true })
    onWatchVisible(value) {
        if (value !== this.visibleTemp) {
            this.visibleTemp = value;
        }
    }

    get dialogTitle() {
        const enumT = { add: '新增', look: '查看', edit: '编辑', auto: '新增' };
        return `${enumT[this.type]}告警器`;
    }

    get isLook() {
        return this.type === 'look';
    }

    // @Watch('detail', { immediate: true })
    // watchdetail(newData) {
    //     if (newData) {
    //         this.submitForm = data;
    //     }
    // }

    /**
     * 获取用户列表
     */
    getUserList() {
        return new Promise((resolve, reject) => {
            this.$axios
                .get('/userManage/user/list')
                .then((res: any) => {
                    if (res) {
                        res.forEach(element => (element.sortId = element.roleCodes?.[0] || '0'));
                        res.sort((a, b) => Number(b.sortId.replace('YH', '')) - Number(a.sortId.replace('YH', '')));
                        this.userStorage = res.filter(item => item.userEnable === '1');
                    }
                    resolve(res);
                })
                .catch(error => {
                    reject(error);
                });
        });
    }

    /**
     * 保存事件
     */
    handleSave(): void {
        if (!this.verify()) return;
        this.loading = true;

        if (this.times) {
            this.submitForm.beginTime = this.times[0];
            this.submitForm.endTime = this.times[1];
        } else {
            this.submitForm.beginTime = null;
            this.submitForm.endTime = null;
        }
        this.submitForm.copyUser = JSON.stringify(this.submitForm.copyUserList);
        this.submitForm.receiveUser = JSON.stringify(this.submitForm.receiveUserList);
        console.log(this.submitForm, 'this.submitForm');
        this.$emit('submit', this.submitForm);
    }

    verify() {
        if (!this.submitForm.alertrtName.trim()) {
            this.yh_message_warn('告警规则名称不能为空!');
            return false;
        }
        if (!this.submitForm.alerterType) {
            this.yh_message_warn('告警渠道不能为空!');
            return false;
        }
        if (this.submitForm.receiveUserList.length === 0) {
            this.yh_message_warn('接收人不能为空!');
            return false;
        }
        if (!this.submitForm.title.trim()) {
            this.yh_message_warn('邮件主题不能为空!');
            return false;
        }
        if (!this.submitForm.context.trim()) {
            this.yh_message_warn('正文不能为空!');
            return false;
        }
        if (!this.submitForm.sendRule.trim()) {
            this.yh_message_warn('发送规则不能为空!');
            return false;
        }
        // if (JSON.stringify(this.submitForm) === JSON.stringify(this.detail)) {
        //     this.yh_message_warn('数据源无修改!');
        //     return false;
        // }
        return true;
    }

    handleReceiveUser(val): void {
        console.log('???');
        console.log(val);
        console.log(this.submitForm.receiveUserList, '!');
    }

    handleReset(): void {
        this.submitForm = {
            alertrtName: '',
            alerterType: 'email', // 告警渠道
            receiveUserList: [], // 接收人
            receiveUser: '',
            copyUserList: [], // 抄送人
            copyUser: '',
            title: '', // 标题
            context: '', // 邮件正文
            sendRule: '', // 发送规则
            beginTime: null, // 告警时段-开始时间
            endTime: null, // 告警时段-结束时间
        };
        this.times = null;
    }

    copyText() {
        const d = document.getElementById('put') as any; // 获取需要复制的元素
        d.select(); // 选中
        document.execCommand('copy'); // 直接复制
        this.yh_message_success('复制成功!');
    }

    /**
     * 关闭dialog事件
     */
    handleCloseDialog(): void {
        this.syncVisible = false;
    }
}
</script>
<style lang="scss" scoped>
.title-with-box {
    border: 1px solid #dcdfe6;
    border-top: none;

    // /deep/ .el-divider--horizontal {
    //     height: 2px;
    // }

    /deep/ .el-divider__text {
        padding: 0 15px;
        font-weight: 600;
        font-size: 15px;
    }

    .frequency-box {
        // margin-bottom: 10px;

        /deep/ .el-col-2 {
            text-align: right;
            padding-right: 20px;
            line-height: 28px;

            .el-icon-plus,
            .el-icon-minus {
                font-size: 17px;
                font-weight: 600;
                cursor: pointer;
            }
        }
    }

    .logic-box {
        display: flex;
        padding: 0 10px;

        .flex1 {
            flex: 1;

            /deep/ .el-button {
                padding: 4px 10px;
                border-radius: 7px;
                .el-icon-plus {
                    font-weight: 600;
                }
            }
        }

        /deep/ .el-card__body {
            padding: 10px;
        }
        p {
            padding-left: 5px;
            margin-bottom: 10px;
        }

        li {
            position: relative;
            border: 1px solid #dcdfe6;
            margin-bottom: -1px;
            border-radius: 4px;
            // height: 30px;
            // line-height: 30px;
            padding: 4px 10px;

            .btn {
                position: absolute;
                right: 0;
                top: 4px;
            }
            .title,
            .link {
                color: #0000ffd7;
            }

            .link {
                cursor: pointer;
                margin-right: 15px;
            }
        }
    }
    .red {
        color: red !important;
    }
}
/deep/ .el-form-item {
    padding: 0 5px;
    margin-bottom: 10px;
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    content: '*' !important;
    color: red !important;
    margin-right: 4px !important;
}

/deep/ .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:after {
    content: '' !important;
}
</style>
